import * as vscode from "vscode";
import { HarmonyPilotGUIWebviewViewProvider } from "../../../src/HarmonyPilotGUIWebviewViewProvider";
import { VsCodeWebviewProtocol } from "../../../src/webviewProtocol";
import { RangeInFileWithContents } from "../../../core";

export const focusInput = (sidebar: HarmonyPilotGUIWebviewViewProvider) => {
    vscode.commands.executeCommand("HarmonyPilot.harmonyPilotGUIView.focus");
    const rangeInFileWithContents = getRangeInFileWithContents();
    addHighlightedCodeToContext(sidebar.webviewProtocol);
}

const addHighlightedCodeToContext = (webviewProtocol: VsCodeWebviewProtocol) => {
    const rangeInFileWithContents = getRangeInFileWithContents();
    if (rangeInFileWithContents) {
      webviewProtocol?.request("highlightedCode", {
        rangeInFileWithContents,
      });
    }
}

function getRangeInFileWithContents(
    allowEmpty?: boolean,
    range?: vscode.Range,
  ): RangeInFileWithContents | null {
    const editor = vscode.window.activeTextEditor;
  
    if (editor) {
      const selection = editor.selection;
      const filepath = editor.document.uri.toString();
  
      if (range) {
        const contents = editor.document.getText(range);
  
        return {
          range: {
            start: {
              line: range.start.line,
              character: range.start.character,
            },
            end: {
              line: range.end.line,
              character: range.end.character,
            },
          },
          filepath,
          contents,
        };
      }
  
      if (selection.isEmpty && !allowEmpty) {
        return null;
      }
  
      // adjust starting position to include indentation
      const start = new vscode.Position(selection.start.line, 0);
      const selectionRange = new vscode.Range(start, selection.end);
      const contents = editor.document.getText(selectionRange);
  
      return {
        filepath,
        contents,
        range: {
          start: {
            line: selection.start.line,
            character: selection.start.character,
          },
          end: {
            line: selection.end.line,
            character: selection.end.character,
          },
        },
      };
    }
  
    return null;
  }
        